package networkSimulation.statistic

import networkSimulation.framework.{Graph, Edge, Node}
import xml.XML
import collection.mutable.HashMap
import java.io.File

/**
 * Created by IntelliJ IDEA.
 * User: Jorick
 * Date: 15-nov-2011
 * Time: 13:52:25
 * To change this template use File | Settings | File Templates.
 */

/**
 * Manager for the statistics.
 *
 * @author  Tim Caljé
 *          Jeroen De Raedt
 *          Jorick Van Aken
 */
class StatisticsManager[N<%Node,E<%Edge[N]](){

  private var counter = 0
  var statistics = new HashMap[String,Statistic[N,E]]()

  /*
  *  Add Statistics to the manager
  */
  def addStatistic(stat : Statistic[N,E]){
    statistics += stat.getClass.toString -> stat
  }

  /*
  *  Generate all the visual statistics for statistics
  */
  def generateStatistics(path:String){
    readXmlFromFiles(path)
    val vis = new VisualStatistics();
    for(key: String <- this.statistics.keySet) {
      statistics(key).generateStatistic(vis,path+"graph")
    }
  }

  /*
  *  Take snapshots from the graph for all the statistics
  */
  def updateStatistics(path:String,graph: Graph[N, E]){
    if(counter==0){
      this.clearData(path)
    }
    for(key: String <- this.statistics.keySet) {
      statistics(key).updateStatistics(graph,key)
    }
    writeXmlToFile(path)
  }

  /*
  *  Write the statistics data to xml
  */
  def writeXmlToFile(path:String){
    var fName = path+"statistics"+ counter+".xml"
    XML.save(fName,toXml())
    counter+=1
  }

  /*
  *  Read the statistics data from xml
  */
  def readXmlFromFiles(path:String){
    var i =0
    while(i!=counter) {
      val data = XML.loadFile(path+"statistics"+ i+".xml")
      loadData(data);
      i+=1
    }
  }

  /*
  *  Loads the xml data into the statistics
  */
  private def loadData(data : xml.NodeSeq){
    for(stat <- (data \\ "Stat")) {
      val k = (stat \\ "@key").text
      statistics(k).loadData(stat)
    }
  }

  /*
  *  Generates xml for the included statistics
  */
  private def toXml(): xml.Elem  ={
     <Stats>
       {
          for(key: String <- this.statistics.keySet)
           yield statistics(key).toXml()
       }
     </Stats>
  }

  /*
  *  Clears the precious written xml's and gif's
  */
  private def clearData(path:String){
    var i = 0
    var file = new File(path+"statistics"+ i+".xml")
     while(file.exists) {
        file.delete()
        i+=1
        file = new File(path+"statistics"+ i+".xml")
     }
    var j = 0
    var file2 = new File(path+"graph"+ j+".gif")
     while(file2.exists) {
        file2.delete()
        j+=1
        file2 = new File(path+"graph"+ j+".gif")
     }
  }
}